package com.chen.auth.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: cgd
 * @description: 用来解决匿名用户访问无权限资源时的异常
 * @date: 2022/3/31 14:18
 * @version: 1.0
 */
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        try {
            Map map = new HashMap();
            map.put("error", "无效token");
            map.put("message", e.getMessage());
            map.put("path", httpServletRequest.getServletPath());
            map.put("timestamp", String.valueOf(System.currentTimeMillis()));
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(httpServletResponse.getOutputStream(), map);
            } catch (Exception ex) {
                throw new ServletException();
            }
        } catch (Exception ex) {
            throw ex;
        }
    }
}
